package com.self.smallma.myblogweb.web;

import com.self.smallma.myblogweb.entity.UserEntity;
import com.self.smallma.myblogweb.util.BizCodeEnum;
import com.self.smallma.myblogweb.service.UserService;
import com.self.smallma.myblogweb.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller

public class LoginController {
    @RequestMapping("/admin")
    public String admin(){

        return "admin/login";
    }

    @Autowired
    UserService userService;
    @PostMapping("/admin/login")
    public String login(LoginVo loginVo, HttpSession session,
                        RedirectAttributes attributes){

        System.out.println(loginVo);
        UserEntity userEntity = userService.login(loginVo);
        if (userEntity!=null){
            userEntity.setPassword(null);
            session.setAttribute("user",userEntity);
            System.out.println(userEntity);
            return "redirect:/index.html";
        }else {
            attributes.addAttribute("message",BizCodeEnum.LOGINACCT_PASSWORD_EXCEPTION.getMsg());
//            session.setAttribute("message",BizCodeEnum.LOGINACCT_PASSWORD_EXCEPTION.getMsg());
            return "redirect:/admin";
        }

    }

    @GetMapping("/admin/out")
    public String out(HttpSession session){
        session.removeAttribute("user");
        //返回首页
        return "redirect:/index.html";
    }
}
